package logic

import (
	"context"
	"encoding/json"
	"time"
	"zhihu/zhihurpc/models/mysql"
	"zhihu/zhihurpc/models/redis"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AnswerslistLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAnswerslistLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AnswerslistLogic {
	return &AnswerslistLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AnswerslistLogic) Answerslist(in *zhihurpc.AnswerslistRequest) (*zhihurpc.AnswerslistResponse, error) {
	// todo: add your logic here and delete this line
	var answers []mysql.Problem
	result, _ := redis.Rdb.Get(l.ctx, "Hot").Result()
	if result == "" {
		mysql.DB.Debug().Limit(10).Order("hot desc").Find(&answers)
		marshal, _ := json.Marshal(answers)
		redis.Rdb.Set(l.ctx, "Hot", marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(result), &answers)
	}
	var answerslist []*zhihurpc.Answerslist
	for _, ans := range answers {
		list := zhihurpc.Answerslist{
			Id:      int64(ans.ID),
			UserId:  ans.UserId,
			Hot:     ans.Hot,
			Content: ans.Content,
		}
		answerslist = append(answerslist, &list)
	}
	return &zhihurpc.AnswerslistResponse{
		List: answerslist,
	}, nil
}
